package comman.duke 
{
	import flash.display.*;
	import flash.events.*;
	import flash.utils.*;
	import comman.duke.FrameItem;
	/**
	 * ...
	 * @author jerry.d
	 */
	public class FrameMgr 
	{
		private var stage:Stage;
		public static var startTime:uint;
		public static var referTime:Number;
		public var itemMap:Object;
		private var items:Vector.<FrameItem>;
		public function FrameMgr() 
		{
			this.items = new Vector.<FrameItem>();
			this.itemMap = {};
		}
		
		public function init(stage:Stage):void{
			this.stage = stage;
			this.stage.addEventListener(Event.ENTER_FRAME, onEnterFrame);
			startTime = referTime = getTimer();
		}
	
		private function onEnterFrame(evt:Event):void{
			var temp:Number = getTimer();
			var delta:Number = temp - referTime;
			var len:Number = this.items.length;
			var item:FrameItem;
			for(var idx:int = len-1; idx >= 0; idx--){
				item = this.items[idx];
				if( item && item.callFun && item.name)
					item.callFun(delta);
				if( len != this.items.length){
					
				}
			}
			referTime = temp;
			
			TickerMgr.Instance.tick(delta);
		}
		
		public function add(item:FrameItem):void{
			if( this.items.indexOf(item) == -1){
				this.items.push(item);
				this.itemMap[item.name] = item;
			}
		}

		public function remove(name:String):void{
			if( this.items.length == 0 ) return;
			var item:FrameItem = this.itemMap[name];
			if( item != null){
				var idx:uint = this.items.indexOf(item);
				if(idx != -1){
					this.items.splice(idx,1);
				}
			}
			delete this.itemMap[name];
		}

		public function has(name:String):Boolean{
			return this.itemMap[name] != null;
		}

		public function pause():void{
			stage.removeEventListener(Event.ENTER_FRAME,onEnterFrame);
		}

		public function resume():void{
			referTime = getTimer();
			stage.addEventListener(Event.ENTER_FRAME,onEnterFrame);
		}
		
		private static var _instance:FrameMgr;
		public static function get Instance():FrameMgr{
			if ( FrameMgr._instance == null ){
				FrameMgr._instance = new FrameMgr();
			}
			return FrameMgr._instance;
		}
		
	}

}